package com.demo.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.demo.dto.UserDTO;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.demo.utils.RedisConstants.LOGIN_TOKEN_KEY;
import static com.demo.utils.RedisConstants.LOGIN_TOKEN_TTL;

/**
 * 配置刷新Token拦截器
 */
public class RefreshTokenInterceptor implements HandlerInterceptor  {

    //TODO 不能使用自动注入StringTemplate
    private StringRedisTemplate stringRedisTemplate;

    public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //TODO 1.获取请求头中的token
        //从前端去拿到头
        String token = request.getHeader("authorization");
        //TODO 第一层拦截不校验 只为了刷新Token
        if (StrUtil.isBlank(token)){
            return true;
        }

        //TODO 2.通过token获取redis中的用户
        Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(LOGIN_TOKEN_KEY + token);
        //3.判断用户是否存在
        if (userMap.isEmpty()){
            return true;
        }

        // TODO 5.将查询到的hash数据转换为UserDTO对象
        UserDTO userDTO = BeanUtil.fillBeanWithMap(userMap, new UserDTO(), false);
        //6.存在，保存user信息到ThreadLocal
        UserHolder.saveUser(userDTO);
        //TODO 7.刷新token有效期 ——有用户进来再次设置过期时间
        stringRedisTemplate.expire(LOGIN_TOKEN_KEY + token,LOGIN_TOKEN_TTL, TimeUnit.MINUTES);
        //8.放行
        return true;
    }
}
